Spiral Galaxy Generation in Ruby
Introduction
The logarithmic spiral form often appears in nature. It is seen in nautilus shells, hurricanes, spiral galaxies, and plants. A simple Ruby program can be used to generate this pattern, and the results can be displayed with the GNU statistics package R.
Ruby Code
# galaxy.rb
# Eric Rollins 2008
# Generates x y coordinates for stars in spiral galaxy.
NUM_STARS = 200000
# logarithmic spiral constants
# http://en.wikipedia.org/wiki/Logarithmic_spiral
A = 1.0
B = 0.20
WINDINGS = 12.4
T_MAX = 2.0 * Math::PI * WINDINGS
# How far stars may be away from spiral arm centers.
DRIFT = 0.3
# Seed random number generator (for repeatabilty).
srand 1234
for s in 1..NUM_STARS
t = T_MAX * rand
x = A * Math.exp(B * t) * Math.cos(t)
x = x + (DRIFT*x*rand) - (DRIFT*x*rand)
y = A * Math.exp(B * t) * Math.sin(t)
y = y + (DRIFT*y*rand) - (DRIFT*y*rand)
# 2 spiral arms
if rand > 0.5
printf "%f %f\n", x, y
else
printf "%f %f\n", -x, -y
end
end
Display in R
ruby galaxy.rb > stars
R
> g <- read.table("stars")
> plot(g,pch=".")